package com.dmai.capacity.platform.user.controller;

import com.dmai.capacity.platform.common.dto.PageResult;
import com.dmai.capacity.platform.common.dto.ResponseEntity;
import com.dmai.capacity.platform.common.model.SysRole;
import com.dmai.capacity.platform.user.service.ISysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author 作者 ftquan E-mail: 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 角色管理
 */
@Slf4j
@RestController
public class SysRoleController {


    @Autowired
    private ISysRoleService roleService;


    /**
     * 查询角色
     *
     * @param params
     * @return
     */
//    @PreAuthorize("hasAuthority('role:get/roles')")
    @GetMapping("/roles")
    public PageResult<SysRole> findRoles(@RequestParam Map<String, Object> params) {
        return roleService.pageRoles(params);
    }


    //    @PreAuthorize("hasAuthority('role:get/roles/getNames')")
    @GetMapping("/roles/{id}")
    public ResponseEntity getRoleNames(@PathVariable(value = "id") Long id) {
        SysRole role = roleService.findById(id);
        return ResponseEntity.succeed(role);
    }

    /**
     * 角色新增
     *
     * @param sysRole
     * @return
     */
//    @PreAuthorize("hasAnyAuthority('role:post/roles','role:put/roles')")
    @PostMapping("/roles")
    public ResponseEntity save(@RequestBody SysRole sysRole) {
        roleService.save(sysRole);

        return ResponseEntity.succeed("操作成功");

    }

    /**
     * 角色新增或者更新
     *
     * @param sysRole
     * @return
     */
//    @PreAuthorize("hasAnyAuthority('role:post/roles','role:put/roles')")
    @PutMapping("/roles")
    public ResponseEntity update(@RequestBody SysRole sysRole) {
        roleService.update(sysRole);

        return ResponseEntity.succeed("操作成功");

    }


    /**
     * 删除角色
     * delete /role/1
     *
     * @param id
     */
//    @PreAuthorize("hasAuthority('role:delete/roles/{id}')")
    @DeleteMapping("/roles/{id}")
    public ResponseEntity deleteRole(@PathVariable(value = "id") Long id) {
        try {
            if (id == 1L) {
                return ResponseEntity.failed("管理员不可以删除");
            }
            roleService.deleteRole(id);
            return ResponseEntity.succeed("操作成功");
        } catch (Exception e) {
            log.error(String.valueOf(e));
            return ResponseEntity.failed("操作失败");
        }
    }
}
